/* Class LoginWidget
 * 
 * Uses a widget action to login client via a simple form
 * 
 * @author David Lindkvist (david.lindkvist@shapeshift.se)
 */

PWF.create('LoginWidget', PWF.SingleActionWidget, 
{
	init: function() {

		/* optional override properties */
		this.width = 300;
		this.height = 120;
	
		/* set action name - we use plain txt files to fake json response */
		//this.setActionName('LoginSuccess.action.txt');
		this.setActionName('LoginFailure.action.txt');
	},
	//implement widget behaviour here - template code is now loaded
	widgetLoaded: function() 
	{
		//grab reference to template input fields (also generates unique ids for the elements)
		this.inputEmail = 	this.getElement('loginWidget_inputEmail');
		this.inputPwd = 	this.getElement('loginWidget_inputPwd');
		this.btnLogin = 	this.getElement('loginWidget_btnLogin');
		this.lblWelcome = 	this.getElement('loginWidget_lblWelcome');	
		this.lblLoggingIn =	this.getElement('loginWidget_lblLoggingIn').hide();
		
		//observe login button
		this.btnLogin.observe('click', this.loginEventListener.bindAsEventListener(this));
	},
	
	/******* LOGIN ACTION METHODS ********************************************************/
	loginEventListener: function(/*Object*/event) 
	{
		//disable button
		this.btnLogin.disable();
		
		//stop form submit
		event.stop();

		//show correct message
		this.lblWelcome.hide();
		this.lblLoggingIn.show();
	
		//prepare and call action
		this.clearActionParameters();
		this.addActionParameter('email', $F(this.inputEmail));
		this.addActionParameter('pwd', $F(this.inputPwd));
		
		//clear pwd field
		this.inputPwd.clear();
		
		this.runAction();	
	},
	onActionSuccess: function(/*Object*/json) 
	{	
		//redirect to success view
		this.redirectToView('loginSuccess.html');
	},
	onActionFailure: function(/*String*/errorMsg)
	{
		this.lblLoggingIn.hide();
		this.lblWelcome.show();
		
		this.lblWelcome.update(errorMsg);
		this.lblWelcome.addClassName('error');
		
		this.btnLogin.enable();
		this.inputPwd.focus();
	}
});
